package infra;

import java.io.File;
import java.io.IOException;

public class FileProjectDAO implements InterfaceProjectDAO
{

    // Constants
    private final String PATH = File.separator + "Documents";

    // Variables
    //Singleton instance
    private static FileProjectDAO instance;

    private FileProjectDAO()
    {
    }

    public FileProjectDAO getInstance()
    {
        if (instance == null)
        {
            instance = new FileProjectDAO();
        }
        return this.instance;
    }

    /**
     * Create a new folder for the new project
     *
     * @param subPath the name of the project, the folder name
     * @return if the operation was sucesfull
     */
    @Override
    public boolean createProj(String subPath)
    {
        File newFolder = new File(PATH + File.separator + subPath);
        if (newFolder.exists())
        {
            return false;
        }
        newFolder.mkdirs();
        return true;
    }

    /**
     * Retrieve the folder of the project
     *
     * @param subPath the name of the folder
     * @return the File of the folder
     * @throws IOException if file not found
     */
    @Override
    public File retrieveProj(String subPath) throws IOException
    {
        if (new File(PATH + File.pathSeparator + subPath).exists())
        {
            return new File(PATH + File.pathSeparator + subPath);
        }
        else
        {
            throw new IOException("Pasta nao encontrada");
        }
    }

    @Override
    public void updateProj(String oldSubPath, String newSubPath) throws IOException
    {
        File oldFolder = new File(PATH + File.pathSeparator + oldSubPath);
        if (oldFolder.exists())
        {
            oldFolder.renameTo(new File(PATH + File.pathSeparator + newSubPath));
        }
        else
        {
            throw new IOException("Pasta nao encontrada");
        }
    }

    /**
     * Delete the folder of the project
     *
     * @param subPath the name of the project
     * @throws IOException if file not found
     */
    @Override
    public void deleteProj(String subPath) throws IOException
    {
        File delFile = new File(PATH + File.pathSeparator + subPath);
        if (delFile.exists())
        {
            delFile.delete();
        }
        else
        {
            throw new IOException("Pasta nao encontrada");
        }
    }

    @Override
    public File[] getAll()
    {
        File motherFolder = new File(PATH);
        if (!motherFolder.exists()) //se a pasta mãe não existe
        {
            motherFolder.mkdirs(); //cria
        }
        return motherFolder.listFiles(); //retorna todas pastas filhas

    }
}
